<template>
  <div class="admin-layout">
    <el-container class="layout-container">
      <el-aside width="220px" class="layout-aside">
        <div class="back-to-main" v-if="isQiankun" @click="backToMain">
          <el-icon><el-icon-back /></el-icon>
          <span>返回主平台</span>
        </div>
        <div class="logo-container">
          <h2>资源管理系统</h2>
        </div>
        <el-menu
          :default-active="activeMenu"
          class="layout-menu"
          router
          background-color="#001529"
          text-color="#fff"
          active-text-color="#409EFF"
        >
          <el-menu-item index="/">
            <el-icon><Coin /></el-icon>
            <span>仪表盘</span>
          </el-menu-item>
          
          <el-sub-menu index="/models">
            <template #title>
              <el-icon><DataAnalysis /></el-icon>
              <span>数据模型</span>
            </template>
            <el-menu-item index="/models">
              <el-icon><Document /></el-icon>
              <span>模型列表</span>
            </el-menu-item>
            <el-menu-item index="/models/create">
              <el-icon><Plus /></el-icon>
              <span>创建模型</span>
            </el-menu-item>
          </el-sub-menu>
          
          <el-sub-menu index="/data" v-if="models.length > 0">
            <template #title>
              <el-icon><Edit /></el-icon>
              <span>数据管理</span>
            </template>
            <el-menu-item 
              v-for="model in models" 
              :key="model.id" 
              :index="`/data/${model.name}`"
            >
            <el-icon><Menu /></el-icon>
              <span>{{ model.displayName }}</span>
            </el-menu-item>
          </el-sub-menu>
          
          <el-menu-item index="/api-docs">
            <el-icon><Document /></el-icon>
            <span>API接口文档</span>
          </el-menu-item>
          
          <el-menu-item index="/settings">
            <el-icon><Setting /></el-icon>
            <span>系统设置</span>
          </el-menu-item>
          
          <el-menu-item index="/ip-authorization">
            <el-icon><Lock /></el-icon>
            <span>IP授权管理</span>
          </el-menu-item>
        </el-menu>
      </el-aside>
      
      <el-container class="layout-main">
        <el-header class="layout-header">
          <div class="header-left">
            <el-breadcrumb separator="/">
              <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
              <el-breadcrumb-item v-if="route.meta.title">{{ route.meta.title }}</el-breadcrumb-item>
            </el-breadcrumb>
          </div>
          <div class="header-right">
            <el-dropdown>
              <span class="user-dropdown">
                管理员 <el-icon><el-icon-arrow-down /></el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item>个人信息</el-dropdown-item>
                  <el-dropdown-item>修改密码</el-dropdown-item>
                  <el-dropdown-item divided>退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </el-header>
        
        <el-main class="layout-content">
          <router-view />
        </el-main>
      </el-container>
    </el-container>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { useModelStore } from '../stores/model'
import { ElMessage, ElLoading } from 'element-plus'
import { Lock } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()
const modelStore = useModelStore()
const models = computed(() => modelStore.models)

const isQiankun = ref(false)

// 检查是否在 qiankun 环境中的函数
const checkQiankunEnv = () => {
  // 检查全局变量
   const inQiankun = Boolean(window.__POWERED_BY_QIANKUN__)
  // console.log('检查 qiankun 环境:', {
  //   inQiankun,
  //   windowObj: window.__POWERED_BY_QIANKUN__,
  //   currentPath: route.path,
  //   currentURL: window.location.href
  // })
  isQiankun.value = inQiankun
}

// 在组件创建时就开始检查
checkQiankunEnv()

// 组件挂载时检查
onMounted(() => {
  checkQiankunEnv()
  // 添加 MutationObserver 监听 DOM 变化
  const observer = new MutationObserver(() => {
    checkQiankunEnv()
  })
  
  observer.observe(document.body, {
    attributes: true,
    childList: true,
    subtree: true
  })
})

// 监听路由变化
watch(
  () => route.path,
  (newPath) => {
    console.log('路由变化:', newPath)
    checkQiankunEnv()
  },
  { immediate: true }
)

// 监听 URL 变化
window.addEventListener('popstate', () => {
  console.log('popstate 事件触发')
  checkQiankunEnv()
})

const activeMenu = computed(() => {
  return route.path
})

const backToMain = () => {
  console.log('尝试返回主应用')
  if (window.__POWERED_BY_QIANKUN__) {
    window.history.pushState({}, '', '/')
    window.dispatchEvent(new PopStateEvent('popstate'))
  }
}

onMounted(async () => {
  let loadingInstance = null
  
  try {
    // 添加加载状态指示
    loadingInstance = ElLoading.service({
      fullscreen: true,
      text: '加载系统数据...'
    })
    
    // 设置超时
    const fetchPromise = modelStore.fetchModels()
    const timeoutPromise = new Promise((_, reject) => {
      setTimeout(() => reject(new Error('加载模型超时')), 5000)
    })
    
    await Promise.race([fetchPromise, timeoutPromise])
  } catch (err) {
    console.error('加载模型失败:', err)
    ElMessage.error('加载系统数据失败，请刷新页面重试')
  } finally {
    // 关闭加载状态
    if (loadingInstance) {
      loadingInstance.close()
    }
  }
})
</script>

<style scoped>
.admin-layout {
  height: 100%;
}

.layout-container {
  height: 100%;
}

.layout-aside {
  background-color: #001529;
  color: white;
  height: 100%;
  overflow-x: hidden;
}

.logo-container {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.layout-menu {
  border-right: none;
}

.layout-header {
  background-color: white;
  border-bottom: 1px solid #e6e6e6;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 20px;
}

.user-dropdown {
  cursor: pointer;
  display: flex;
  align-items: center;
}

.layout-content {
  background-color: #f0f2f5;
  padding: 20px;
}

.back-to-main {
  padding: 12px 20px;
  display: flex;
  align-items: center;
  gap: 8px;
  color: #fff;
  cursor: pointer;
  transition: all 0.3s;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.back-to-main:hover {
  background-color: rgba(255, 255, 255, 0.1);
  color: #409EFF;
}

.back-to-main .el-icon {
  font-size: 16px;
}
</style> 